<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getEmployees">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

    <!--列表-->
    <el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="员工姓名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="email" label="员工邮箱" width="180" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="员工电话" width="180" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="180" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span style="color: #5daf34" v-if="scope.row.state === 0">任职</span>
          <span style="color:red" v-else-if="scope.row.state === -1">离职</span>
          <span style="color:dimgrey" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :page-size="page"
               :pageSize="pageSize"
						   :total="total"
						   style="float:right;">
			</el-pagination>
		</el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="employeeFormVisible" :close-on-click-modal="false">
      <el-form :model="employeeForm" label-width="80px" :rules="employeeFormRules" ref="employeeForm">
        <el-form-item label="员工姓名" prop="username">
          <el-input v-model="employeeForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工邮箱" prop="email">
          <el-input v-model="employeeForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工电话" prop="phone">
          <el-input v-model="employeeForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="employeeForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="employeeForm.state">
            <el-radio class="radio" :label="0">任职</el-radio>
            <el-radio class="radio" :label="-1">离职</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="employeeFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="employeeSubmit" :loading="employeeLoading">提交</el-button>
      </div>
    </el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, employeeEmployee, addEmployee } from '../../api/api';

	export default {
		data() {
      return {
        filters: {
          title: ' ',
          filters: {
            keyword:" "
          },
        },
				employees: [],
				total: 0,
        pageSize:10,
				page: 1,
				listLoading: false,
				sels: [],//列表选中行

				employeeFormVisible: false,//编辑界面是否显示
				employeeLoading: false,
				employeeFormRules: {
					username: [
						{ required: true, message: '请输入员工姓名', trigger: 'blur' }
					],
          email: [
            {required: true, message: '请输入员工邮箱', trigger: 'blur'}
          ],
          phone: [
            {required: true, message: '请输入员工电话', trigger: 'blur'}
          ]
				},
				//编辑界面数据
				employeeForm: {
            id: null,
            username: "",
            email: "",
            phone: "",
            age: null,
            state: 0,
				},
			}
		},
		methods: {
			handleCurrentChange(val) {
				this.page = val;
				this.getEmployees();
			},
			//获取员工列表
			getEmployees() {
				let para = {
					currentPage: this.page,
          keyword: this.filters.keyword,
          pageSize:this.pageSize
				};
				this.listLoading = true;//开启忙等框
				this.$http.post("/employee",para)
					.then(result=>{
						result = result.data;//PageList{total rows}
						this.employees = result.rows;
                        this.listLoading = false;//关闭忙等框
						this.total = result.total;

					})
					.catch(result=>{
					    console.log(result);
					    alert("操作异常，已滚出！");
					})

			},
      // 删除
      handleDel: function (index, row) {
        this.$confirm('请确认你是否为手贱误点?', '祖安提示', {
          type: 'warning'
        }).then(() => { // 点击确定
          this.listLoading = true;
          //NProgress.start();
          this.$http.delete("/employee/" + row.id)
              .then(result => {
                this.listLoading = false;  // 关闭忙等框
                result = result.data;  // 操作失败
                if (result.success) {
                  this.$message({
                    message: "操作成功",
                    type: "success"
                  });
                } else {
                  this.$message({
                    message: result.message, // 自己的业务出错
                    type: "error",
                  });
                }
                // 刷新页面并定位到第一页
                this.page= 1;
                this.getEmployees();
              })
        }).catch(result => {
          this.listLoading = false;  // 关闭忙等框
          this.$message({
            message: "操作异常，已滚出",
            type: "error"
          });
          // 操作失败刷新页面并定位到第一页
          this.page = 1;
          this.getEmployees();
        }).catch(() => {  // 点击取消

        });
      },
			//显示编辑界面
			handleEdit: function (index, row) {
				this.employeeFormVisible = true;
				//Object.assign 克隆
				this.employeeForm = Object.assign({}, row);//回显
			},
			//显示新增界面
			handleAdd: function () {
				this.employeeFormVisible = true;
				this.employeeForm = {//清空历史遗留数据
          id: null,
          username: "",
          email: "",
          phone: "",
          age: null,
          state: 0,
				};
			},
      // 提交表单
      employeeSubmit: function () {
        this.$refs.employeeForm.validate((valid) => {  // 开启表单检验
          if (valid) {  // 校验通过
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.employeeLoading = true;// 开启忙等框
              let para = Object.assign({}, this.employeeForm);// 克隆表单数据
              // 处理后台需要的数据格式
              if(para.parent){
                let parent = para.parent;
                // 获取数组的最后一个
                let pid = parent[parent.length-1];
                // 重新设置parent的值
                para.parent = {"id":pid};
              }

              this.$http.put("/employee",para)
                  .then(result=>{
                    result = result.data;//AjaxResult
                    this.employeeLoading = false;// 关闭忙等框
                    this.employeeFormVisible = false;// 关闭弹出框
                    if(result.success){
                      this.$message({
                        message: '操作成功',
                        type: 'success'
                      });
                    }else{
                      this.$message({
                        message: result.message,// 提示业务出错
                        type: 'error'
                      });
                    }
                    // 刷新页面并定位到第一页
                    this.page = 1;
                    this.getEmployees();

                  })
                  .catch(result=>{
                    this.employeeLoading = false;// 关闭忙等框
                    this.$message({
                      message: '操作异常，已滚出',
                      type: 'error'
                    });
                  })
            });
          }
        });
      },
      selsChange: function (sels) {// 当前已经选中的所有行的数据
        this.sels = sels;
      },

      //批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中的记录吗？', '祖安提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //NProgress.start();
          this.$http.patch("/employee", ids)
              .then(result => {
                this.listLoading = false;
                // 判断业务是否正常
                result = result.data;
                if (result.success) {
                  this.$message({
                    message: "操作成功",
                    type: "success"
                  });
                } else {
                  this.$message({
                    message: result.message,  // 提示代码错误
                    type: "error"
                  });
                }
                // 刷新页面并定位到第一页
                this.page=1;
                this.getEmployees();
              })
        }).catch(() => {
          this.listLoading = false;  // 关闭忙等框
          this.$message({
            message: "操作异常，已滚出",
            type: "error"
          });
          this.page = 1;
          this.getEmployees();
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getEmployees();
		}
	}

</script>

<style scoped>


</style>